from django.core.management.base import BaseCommand
from django.db import connection, transaction
import os
from django.core.management import call_command
import io
from tsl_backend.frontend_api.models.workorder import Detail
import tsl_backend.frontend_api.models.route as routes


class Command(BaseCommand):
    help = 'Update ori fg article for exist order detail'

    def handle(self, *args, **options):

        master_dict = {
            master.id : master
            for master in routes.Master.objects.all()
        }

        updates = []

        for detail in Detail.objects.all():
            if detail.ori_fg_article is None:
                detail.ori_fg_article = master_dict.get(detail.master.id)
                updates.append(detail)

        Detail.objects.bulk_update(updates,['ori_fg_article'])

        self.stdout.write(self.style.SUCCESS('Detail ori_fg_article update complete.'))